package com.common.dongqiuhui.apps.comm.tools;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.KeyguardManager;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.StateListDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.provider.MediaStore;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.URLUtil;
import android.widget.EditText;

import com.common.dongqiuhui.apps.comm.constants.KeysConstans;
import com.common.dongqiuhui.apps.comm.util.ParseUtil;
import com.common.dongqiuhui.apps.comm.util.SharedPreferencesUtil;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.Character.UnicodeBlock;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class BallUtil {

	private BallUtil() {
	}

	private static char[] base64EncodeChars = new char[] { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',
			'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g',
			'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1',
			'2', '3', '4', '5', '6', '7', '8', '9', '+', '/' };

	private static byte[] base64DecodeChars = new byte[] { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
			-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
			-1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4,
			5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26,
			27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1,
			-1, -1, -1 };
	public static final SimpleDateFormat FORMAT = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
	public static final SimpleDateFormat IMAGE_DATE_FORMAT = new SimpleDateFormat("yyyy年MM月dd日", Locale.getDefault());
	public static SimpleDateFormat mDateFormat = new SimpleDateFormat("yyyy年M月d日", Locale.getDefault());
	private final static SimpleDateFormat dateFormater = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault());
	private final static SimpleDateFormat dateFormater3 = new SimpleDateFormat("HH:mm", Locale.getDefault());
	private static final long MINUTE_AGO = 1 * 60 * 1000; // 1分钟以前

	private static final long HOUR_AGO = 1 * 60 * 60 * 1000; // 1小时以前

	private static final long DAY_AGO = 24 * 60 * 60 * 1000; // 24小时以前

	private static final long FIVE_DAY_AGO = 5 * 24 * 60 * 60 * 1000; // 5天以前

	private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd hh:mm", Locale.getDefault());

	private static final SimpleDateFormat UPLOAD_DATE_FORMAT = new SimpleDateFormat("yyyy/MMdd", Locale.getDefault());

	/**
	 * 去除List重复内容
	 * 
	 * @param arlList
	 * @param list
	 * @return 返回去除重复之后的list
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static ArrayList removeDuplicate(ArrayList arlList, ArrayList list) {
		for (Object object : list) {
			if (!arlList.contains(object)) {
				arlList.add(object);
			}
		}
		return arlList;
	}

	/**
	 * 设置cookies
	 * 
	 * @param context
	 * @param url
	 *            需要设置的网页地址
	 * @param cookie
	 *            内容
	 */
	public static void setCookies(Context context, String url, String cookie) {
		if (cookie != null && !cookie.trim().equals("")) {
			CookieSyncManager.createInstance(context); // 得到同步cookie的对象
			CookieManager cookieManager = CookieManager.getInstance(); // 管理cookie的对象
			// cookieManager.setAcceptCookie(true);
			// cookieManager.removeSessionCookie();//移除
			cookieManager.setCookie(url, encodeCookieKV("NL", cookie));

			// 设置cookie
			// cookieManager.setCookie(url, "NL=" + cookie);
			// cookieManager.setCookie(url, "domain=" + ".babytree.com");
			// cookieManager.setCookie(u rl, "version=" + "0");
			// cookieManager.setCookie(url, "path=" + "/");
			// cookieManager.setCookie(url, "expiry=" + "86400");
			CookieSyncManager.getInstance().sync();
		}
	}

	/**
	 * 编码key value
	 * <p>
	 * <b>Note:</b> 解决网站cookie验证【NL与L cookie】，严重延迟问题
	 * 
	 * <p>
	 * 【Cookie问题--里程碑】
	 */
	private static String encodeCookieKV(String key, String value) {
		String encodeKey = URLEncoder.encode(key);// encode Key
		String encodeValue = URLEncoder.encode(value);// encode Value
		return encodeKey + "=" + encodeValue;
	}

	/**
	 * 清除cookies
	 * 
	 * @param context
	 */
	public static void clearCookies(Context context) {
		CookieSyncManager.createInstance(context); // 得到同步cookie的对象
		CookieManager cookieManager = CookieManager.getInstance(); // 管理cookie的对象
		cookieManager.removeAllCookie();
	}

	/**
	 * 返回多少时间 多少秒前 多少小时前
	 * 
	 * @param time
	 * @return
	 */
	public static String formatTimestamp(long time) {
		long currentTime = System.currentTimeMillis();
		long serverTime = time * 1000;
		long intervalTime = currentTime - serverTime;
		Log.i("fyh", "serverTime=" + time);
		Log.i("fyh", "currentTime=" + currentTime);

		if (intervalTime < MINUTE_AGO) {
			long l = (intervalTime % (1000 * 60)) / 1000;
			Log.i("fyh", "l=" + l);
			if (l > 0)
				return l + "秒前";
			else
				return "1秒前";
		} else if (intervalTime < HOUR_AGO) {
			return (intervalTime % (1000 * 60 * 60)) / (1000 * 60) + "分钟前";
		} else if (intervalTime < DAY_AGO) {
			return (intervalTime % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60) + "小时前";
		} else if (intervalTime < FIVE_DAY_AGO) {
			return intervalTime / (1000 * 60 * 60 * 24) + "天前";
		} else {
			return FORMAT.format(new Date(serverTime));
		}
	}

	public static String formatTimestampAten(long time) {
		long currentTime = System.currentTimeMillis();
		long serverTime = time * 1000;
		long intervalTime = currentTime - serverTime;
		if (intervalTime < MINUTE_AGO) {
			long l = (intervalTime % (1000 * 60)) / 1000;
			if (l > 0)
				return l + "秒前";
			else
				return "1秒前";
		} else if (intervalTime < HOUR_AGO) {
			return (intervalTime % (1000 * 60 * 60)) / (1000 * 60) + "分钟前";
		} else if (intervalTime < DAY_AGO) {
			return (intervalTime % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60) + "小时前";
		} else if (intervalTime < FIVE_DAY_AGO) {
			return intervalTime / (1000 * 60 * 60 * 24) + "天前";
		} else {
			return dateFormater.format(new Date(serverTime));
		}
	}

	public static String formatImageTime(long time) {
		long serverTime = time * 1000;
		return IMAGE_DATE_FORMAT.format(new Date(serverTime));
	}

	public static String formatUploadTime(long time) {
		return UPLOAD_DATE_FORMAT.format(new Date(time));
	}

	public static String formatNYRtime(long time) {
		long serverTime = time * 1000;
		return FORMAT.format(new Date(serverTime));
	}

	public static String formatNYHMRtime(long time) {
		long serverTime = time * 1000;
		Date date = new Date(serverTime);
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		String timeStr = format.format(date);
		return timeStr;
	}

	/**
	 * 返回带中文的日期时分
	 */
	public static String formatNYT_CH(long time) {
		long serverTime = time * 1000;
		Date date = new Date(serverTime);
		SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日 HH:mm");
		String timeStr = format.format(date);
		return timeStr;
	}
	
	/**
	 * 返回带中文的日期
	 */
	public static String formatNY_CH(long time) {
		long serverTime = time * 1000;
		Date date = new Date(serverTime);
		SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日");
		String timeStr = format.format(date);
		return timeStr;
	}

	/**
	 * 返回带中文的日期
	 */
	public static String formatNY_CH1(long time) {
		long serverTime = time;
		Date date = new Date(serverTime);
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
		String timeStr = format.format(date);
		return timeStr;
	}

	public static String formatNY_POINT(long time) {
		long serverTime = time * 1000;
		Date date = new Date(serverTime);
		SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd");
		String timeStr = format.format(date);
		return timeStr;
	}

	public static String formatImageTimestamp(long time) {
		return DATE_FORMAT.format(new Date(time * 1000));
	}

	public static String formatNY(long time) {
		long serverTime = time * 1000;
		Date date = new Date(serverTime);
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		String timeStr = format.format(date);
		return timeStr;
	}

	// 按中国时区算时间

	public static String formatNY2(long time) {
		long serverTime = time * 1000;
		Date date = new Date(serverTime);
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		format.setTimeZone(TimeZone.getTimeZone("GMT+8"));
		String timeStr = format.format(date);
		return timeStr;
	}

	public static String formatYeartime(long time) {
		long serverTime = time * 1000;
		Date date = new Date(serverTime);
		SimpleDateFormat format = new SimpleDateFormat("yyyy");
		String timeStr = format.format(date);
		return timeStr;
	}

	public static String nowBabyAge(String perdate, String curdata, String babyBir) {
		String babyyear = babyBir.substring(0, 4);
		String babymonth = babyBir.substring(5, 6).equalsIgnoreCase("0") ? babyBir.substring(6, 7)
				: babyBir.substring(5, 7);
		String babyday = babyBir.substring(8, 9).equalsIgnoreCase("0") ? babyBir.substring(9, 10)
				: babyBir.substring(8, 10);
		String preyear = perdate.substring(0, 4);
		String permonth = perdate.substring(5, 6).equalsIgnoreCase("0") ? perdate.substring(6, 7)
				: perdate.substring(5, 7);
		String perday = perdate.substring(8, 9).equalsIgnoreCase("0") ? perdate.substring(9, 10)
				: perdate.substring(8, 10);

		String curyear = curdata.substring(0, 4);
		String curmonth = curdata.substring(5, 6).equalsIgnoreCase("0") ? curdata.substring(6, 7)
				: curdata.substring(5, 7);
		String curday = curdata.substring(8, 9).equalsIgnoreCase("0") ? curdata.substring(9, 10)
				: curdata.substring(8, 10);

		return "";
	}

	/**
	 * 网络状态判断
	 * 
	 * @param context
	 * @return
	 */
	public static boolean hasNetwork(Context context) {
		ConnectivityManager manager = (ConnectivityManager) context.getApplicationContext()
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (manager == null) {
			return false;
		}
		NetworkInfo networkinfo = manager.getActiveNetworkInfo();
		if (networkinfo == null || !networkinfo.isAvailable()) {
			return false;
		}
		return true;

	}

	/**
	 * 返回当前程序版本名
	 */
	public static String getAppVersionName(Context context) {
		try {
			PackageManager pm = context.getPackageManager();
			PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
			return pi.versionName;
		} catch (Exception e) {
			return "";
		}
	}

	/**
	 * 返回当前程序版本号
	 */
	public static String getAppVersionCode(Context context) {
		try {
			PackageManager pm = context.getPackageManager();
			PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
			return String.valueOf(pi.versionCode);
		} catch (Exception e) {
			e.printStackTrace();
			return "0";
		}
	}

	/**
	 * 返回mac地址
	 */
	public static String getMacAddress(Context context) {
		String mac = "";
		try {
			WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
			WifiInfo info = wifi.getConnectionInfo();
			mac = info.getMacAddress();
			if (mac == null || mac.equalsIgnoreCase("null")) {
				mac = "";
			}
			return mac;
		} catch (Exception e) {
			return mac;
		}
	}

	/**
	 * 旋转一张图片
	 * 
	 * @param srcBitmap
	 * @param degrees
	 * @return
	 */
	public final static Bitmap rotationBitmap(Bitmap srcBitmap, float degrees) {
		Bitmap result = null;
		if (degrees != 0 && srcBitmap != null) {
			Matrix m = new Matrix();
			m.setRotate(degrees, (float) srcBitmap.getWidth() / 2, (float) srcBitmap.getHeight() / 2);
			try {
				Bitmap b2 = Bitmap.createBitmap(srcBitmap, 0, 0, srcBitmap.getWidth(), srcBitmap.getHeight(), m, true);
				if (srcBitmap != b2) {
					srcBitmap.recycle(); // Android开发网再次提示Bitmap操作完应该显示的释放
					srcBitmap = b2;
				}
				result = b2;
			} catch (OutOfMemoryError ex) {
				// Android123建议大家如何出现了内存不足异常，最好return 原始的bitmap对象。.
				ex.printStackTrace();
			}
		}
		return result;
	}

	public final static Bitmap rotationBitmap2(Bitmap srcBitmap, float degrees) {
		Bitmap result = null;
		if (degrees != 0 && srcBitmap != null) {
			Matrix m = new Matrix();
			m.setRotate(degrees, (float) srcBitmap.getWidth() / 2, (float) srcBitmap.getHeight() / 2);
			try {
				result = Bitmap.createBitmap(srcBitmap, 0, 0, srcBitmap.getWidth(), srcBitmap.getHeight(), m, true);
			} catch (OutOfMemoryError ex) {
				ex.printStackTrace();
			}
		}
		return result;
	}

	/**
	 * 根据原图缩放出一张制定尺寸的Bitmap
	 * 
	 * @param src
	 *            原始图片
	 * @param newWidth
	 *            新宽度
	 * @param newHeight
	 *            新高度,被忽略，采用等比例缩放
	 * @return 缩放后的Bitmap
	 */
	public static final Bitmap scaleBitmap(Bitmap src, int newWidth, int newHeight) {
		// 获得图片的宽高
		float width = src.getWidth();
		float height = src.getHeight();
		// // 设置想要的大小
		newHeight = (int) ((newWidth / width) * height);
		// 计算缩放比例
		float scaleWidth = ((float) newWidth) / width;
		float scaleHeight = ((float) newHeight) / height;
		// 取得想要缩放的matrix参数
		Matrix matrix = new Matrix();
		matrix.postScale(scaleWidth, scaleHeight);

		// 得到新的图片
		Bitmap newbm = Bitmap.createBitmap(src, 0, 0, (int) width, (int) height, matrix, true);
		return newbm;
	}

	public static int computeSampleSize(BitmapFactory.Options options, int minSideLength, int maxNumOfPixels) {
		int initialSize = computeInitialSampleSize(options, minSideLength, maxNumOfPixels);
		int roundedSize;
		if (initialSize <= 8) {
			roundedSize = 1;
			while (roundedSize < initialSize) {
				roundedSize <<= 1;
			}
		} else {
			roundedSize = (initialSize + 7) / 8 * 8;
		}
		return roundedSize;
	}

	private static int computeInitialSampleSize(BitmapFactory.Options options, int minSideLength, int maxNumOfPixels) {
		double w = options.outWidth;
		double h = options.outHeight;
		int lowerBound = (maxNumOfPixels == -1) ? 1 : (int) Math.ceil(Math.sqrt(w * h / maxNumOfPixels));
		int upperBound = (minSideLength == -1) ? 128
				: (int) Math.min(Math.floor(w / minSideLength), Math.floor(h / minSideLength));
		if (upperBound < lowerBound) {
			return lowerBound;
		}
		if ((maxNumOfPixels == -1) && (minSideLength == -1)) {
			return 1;
		} else if (minSideLength == -1) {
			return lowerBound;
		} else {
			return upperBound;
		}
	}

	public static void copyFile(File fromFile, File toFile, Boolean rewrite) {
		if (!fromFile.exists()) {
			return;
		}
		if (!fromFile.isFile()) {
			return;
		}
		if (!fromFile.canRead()) {
			return;
		}
		if (!toFile.getParentFile().exists()) {
			toFile.getParentFile().mkdirs();
		}
		if (toFile.exists() && rewrite) {
			toFile.delete();
		}

		try {
			java.io.FileInputStream fosfrom = new java.io.FileInputStream(fromFile);
			FileOutputStream fosto = new FileOutputStream(toFile);
			byte bt[] = new byte[1024];
			int c;
			while ((c = fosfrom.read(bt)) > 0) {
				fosto.write(bt, 0, c); // 将内容写到新文件当中
			}
			fosfrom.close();
			fosto.close();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	public static int getBetweenDays(long l1, long l2) throws ParseException {
		int betweenDays = 0;
		Calendar c1 = Calendar.getInstance();
		Calendar c2 = Calendar.getInstance();
		c1.setTimeInMillis(l1);
		c2.setTimeInMillis(l2);
		// 保证第二个时间一定大于第一个时间
		if (c1.after(c2)) {
			c1 = c2;
			c2.setTimeInMillis(l1);
		}
		BallLog.i("l2=" + l2);
		BallLog.i("l1=" + l1);

		int betweenYears = c2.get(Calendar.YEAR) - c1.get(Calendar.YEAR);
		betweenDays = c2.get(Calendar.DAY_OF_YEAR) - c1.get(Calendar.DAY_OF_YEAR);
		for (int i = 0; i < betweenYears; i++) {
			c1.set(Calendar.YEAR, (c1.get(Calendar.YEAR) + 1));
			betweenDays += c1.getMaximum(Calendar.DAY_OF_YEAR);
		}
		BallLog.i("betweenDays=" + betweenDays);
		BallLog.i("betweenYears=" + betweenYears);
		return betweenDays;
	}

	/**
	 * 大于2天显示完整时间 2天内显示昨天 HH:mm 1天内显示 HH:mm
	 *
	 * @param time
	 *            时间秒数
	 * @return
	 */
	public static String formatTimestampForNotice(long time) {
		long currentTime = System.currentTimeMillis();
		long serverTime = time * 1000;
		long intervalTime = currentTime - serverTime;
		if (intervalTime / DAY_AGO < 1) {
			return dateFormater3.format(new Date(serverTime));
		} else if (intervalTime / DAY_AGO < 2) {
			return "昨天 " + dateFormater3.format(new Date(serverTime));
		} else {
			return dateFormater.format(new Date(serverTime));
		}
	}

	public static String timestempToStringMore(String time) {
		return dateFormater.format(new Date(BallUtil.parseLong(time) * 1000));
	}

	public static String timestempToStringMore2(String time) {
		return dateFormater.format(new Date(BallUtil.parseLong(time)));
	}

	/**
	 * 毫秒数转时间字符(2011-01-01格式)
	 *
	 * @author wangshuaibo
	 * @param time
	 * @return
	 */
	public static String timestempToString(long time) {
		try {
			return FORMAT.format(new Date(time));
		} catch (Exception ex) {
			return "";
		}
	}

	/**
	 * 判断android设备中是否有相应的应用来处理这个Intent。
	 *
	 * @param context
	 * @param intent
	 * @return
	 */
	public static boolean hasIntentActivities(Context context, Intent intent) {
		PackageManager packageManager = context.getPackageManager();
		List<ResolveInfo> list = packageManager.queryIntentActivities(intent, 0);

		return list.size() > 0;
	}

	/**
	 * 获取网络类型
	 */
	public static int getNetWork(Context context) {
		ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo info = manager.getActiveNetworkInfo();
		if (info == null)
			return -1;
		String type = info.getTypeName();
		if (type.equals("WIFI")) {
			return 4;// wifi
		} else if (type.equals("MOBILE")) {
			return getNetworkClass(info.getType());
		}
		return -1;
	}

	public static int getNetworkClass(int networkType) {
		switch (networkType) {
		case TelephonyManager.NETWORK_TYPE_GPRS:
		case TelephonyManager.NETWORK_TYPE_EDGE:
		case TelephonyManager.NETWORK_TYPE_CDMA:
		case TelephonyManager.NETWORK_TYPE_1xRTT:
		case TelephonyManager.NETWORK_TYPE_IDEN:
			return 1;// 2G
		case TelephonyManager.NETWORK_TYPE_UMTS:
		case TelephonyManager.NETWORK_TYPE_EVDO_0:
		case TelephonyManager.NETWORK_TYPE_EVDO_A:
		case TelephonyManager.NETWORK_TYPE_HSDPA:
		case TelephonyManager.NETWORK_TYPE_HSUPA:
		case TelephonyManager.NETWORK_TYPE_HSPA:
		case TelephonyManager.NETWORK_TYPE_EVDO_B:
		case TelephonyManager.NETWORK_TYPE_EHRPD:
		case TelephonyManager.NETWORK_TYPE_HSPAP:
			return 2;// 3G
		case TelephonyManager.NETWORK_TYPE_LTE:
			return 3;// 4G
		default:
			return 0;
		}
	}

	/**
	 * 获取网络
	 *
	 * @param context
	 * @return
	 */
	public static String getExtraInfo(Context context) {
		ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo nwInfo = connectivity.getActiveNetworkInfo();
		if (nwInfo == null) {
			return null;
		}
		String extraInfo = nwInfo.getExtraInfo();
		String typeName = nwInfo.getTypeName();
		if (typeName != null && typeName.equalsIgnoreCase("WIFI")) {
			return typeName;
		}
		return extraInfo;
	}

	/**
	 * 通过服务器返回的信息status来判定message是什么提示
	 */
	public static String getMessage(String status) {
		String message = null;
		if (status != null) {
			if (status.equals("failed")) {
				message = "操作失败";
			} else if (status.equals("nonLogin")) {
				message = "没有登录";
			} else if (status.equals("invalidParams")) {
				message = "参数错误";
			} else if (status.equals("invalid_token")) {
				message = "token验证不通过";
			} else if (status.equals("no_bind")) {
				message = "没有绑定用户";
			} else if (status.equals("already_binded")) {
				message = "已经绑定了";
			} else if (status.equals("wrong_email_or_password")) {
				message = "用户名或密码错误";
			} else if (status.equals("bind_failed")) {
				message = "绑定失败";
			} else if (status.equals("email_empty")) {
				message = "您还没有填写邮箱";
			} else if (status.equals("email_format_illegal")) {
				message = "邮箱的格式有误";
			} else if (status.equals("email_to_lang")) {
				message = "邮箱过长";
			} else if (status.equals("email_already_exists")) {
				message = "该邮箱已有人注册";
			} else if (status.equals("email_blocked")) {
				message = "邮箱中含有违禁语";
			} else if (status.equals("nickname_empty")) {
				message = "您还没有填写昵称";
			} else if (status.equals("nickname_too_short")) {
				message = "昵称过短";
			} else if (status.equals("nickname_too_long")) {
				message = "昵称过长";
			} else if (status.equals("nickname_too_invalid")) {
				message = "此昵称不可用";
			} else if (status.equals("nickname_blocked")) {
				message = "昵称中含有违禁语";
			} else if (status.equals("nickname_special_char")) {
				message = "昵称中不能包含特殊符号、空格";
			} else if (status.equals("nickname_whitescpace")) {
				message = "昵称中不能包含空格";
			} else if (status.equals("nickname_alpeady_exists")) {
				message = "该昵称已有人注册，您可以在昵称后面加上一些数字来避免重复，如宝宝生日或您的纪念日";
			} else if (status.equals("reg_failed")) {
				message = "注册失败";
			} else if (status.equals("max_follow_group")) {
				message = "已经达到圈子数上限";
			} else if (status.equals("community_no_join_group")) {
				message = "只有加入这个帮才能发帖回帖";
			} else if (status.equals("owner_cannot_quit")) {
				message = "不能退出自己创建的圈子";
			} else if (status.equals("forbidden")) {
				message = "话题太辣，请改改再发~";
			} else if (status.equals("blockedUser") || status.equals("no_posting") || status.equals("suspended")) {
				message = "啊呀呀，辣妈被禁足啦，请联系管管~";
			} else if (status.equals("nickname_already_exists")) {
				message = "用户名已存在";

			} else if (status.equals("nickname_is_modify_this_month")) {
				message = "用户名一个月只能修改一次";
			} else if (status.equals("user_deleted")) {
				message = "用户已被删除";
			} else {
				message = "请求失败";
			}
		}
		return message;
	}

	/**
	 * 启动新的activity
	 *
	 * @param activity
	 * @param intent
	 * @param forResult
	 *            是否启用startActivityForResult方法
	 * @param requestCode
	 *            请求码:若forResult为false时候，不需要使用startActivityForResult方法，此设置无效
	 */
	public static void launch(Activity activity, Intent intent, boolean forResult, int requestCode) {
		if (forResult) {
			activity.startActivityForResult(intent, requestCode);
		} else {
			activity.startActivity(intent);
		}
	}

	public static void launch(Context activity, Intent intent) {
		activity.startActivity(intent);
	}

	/**
	 * 设置html格式的颜色值
	 *
	 * @param text
	 *            需要设置的文本
	 * @param color
	 *            需要设置的颜色：#ffffff
	 * @return
	 */
	public static String setHtmlColor(String text, String color) {
		return "<font color=\"" + color + "\">" + text + "</font>";
	}

	public static boolean checkEmail(String email) {
		String regex = "^[A-Za-z0-9]+([._+-]*[A-Za-z0-9])*@([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])(\\.{1,3}[A-Za-z]{2,6}){1,2}$";
		// String regex = "\\w+@(\\w+.)+[a-z]{2,3}";
		Pattern p = Pattern.compile(regex);
		Matcher m = p.matcher(email);
		return m.matches();
	}

	/**
	 * 比较是否是同一天
	 *
	 * @return true相同的一天 false不同的一天
	 */
	public static boolean isSameDay(long time) {
		long timeMillis = System.currentTimeMillis();
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
		String sp_time = sf.format(time * 1000);
		String current_time = sf.format(timeMillis);
		if (!sp_time.equals(current_time)) {
			// 不同一天
			return false;
		}
		return true;
	}

	/**
	 * 比较是否是同一天
	 *
	 * @return true相同的一天 false不同的一天
	 */
	public static boolean isSameDay(long time1, long time2) {
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
		String sp_time = sf.format(time1 * 1000);
		String current_time = sf.format(time2 * 1000);
		if (!sp_time.equals(current_time)) {
			// 不同一天
			return false;
		}
		return true;
	}

	/**
	 * 时间转换为毫秒数
	 */
	public static long timeToMillionSeconds(String time) {
		long millionSeconds = 0;

		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMd");
		try {
			millionSeconds = sdf.parse(time).getTime();
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} // 毫秒
		return millionSeconds;
	}

	/**
	 * 加帮字的方法
	 */
	public static String changeToBang(String name) {
		// if(name==null||name.equalsIgnoreCase("")){
		// return "";
		// }
		// try {
		// String last=name.substring(name.length()-1, name.length());
		// char c=name.charAt(name.length()-1);
		//
		// for(int i=0;i<names.length;i++){
		// if(last.equalsIgnoreCase(names[i])){
		// return name.substring(0, name.length()-1)+"帮";
		// }
		// }
		// if(!isBiaoQing(last)) {
		// return name;
		// }else if(last.equalsIgnoreCase("帮")){
		// return name;
		// }else{
		// return name+"帮";
		// }
		// } catch (Exception e) {
		// // TODO: handle exception
		// }
		return name;
	}

	public static boolean isBiaoQing(String lastString) {
		if (lastString != null) {
			final String reg = "\\d+\\.{0,1}\\d*";
			String ziMu = "[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ]";
			boolean isDigits = lastString.matches(reg);
			String regEx = "[\\u4e00-\\u9fa5]";
			Pattern p = Pattern.compile(regEx);
			Matcher m = p.matcher(lastString);
			if (m.find() || isDigits == true || lastString.matches(ziMu) == true) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 时间转换为毫秒数
	 */
	public static long timeToMillionSeconds1(String time) {
		long millionSeconds = 0;

		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		try {
			millionSeconds = sdf.parse(time).getTime();
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} // 毫秒
		return millionSeconds;
	}

	/**
	 * 时间转换为毫秒数
	 */
	public static long timeToMillionSeconds2(String time) {
		long millionSeconds = 0;

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		try {
			millionSeconds = sdf.parse(time).getTime();
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} // 毫秒
		return millionSeconds / 1000;
	}

	public static int dip2px(Context context, int size) {
		return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, size,
				context.getResources().getDisplayMetrics());
	}

	// 获取设备唯一Id
	public static String getMIEI(Context context) {
		TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
		// String non=tm.getDeviceId();//imei=868943005484708
		return getMD5Str(tm.getDeviceId()) + "_lama_android";
	}

	// 获取设备唯一Id
	public static String getPhoneMIEI(Context context) {
		TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
		// String non=tm.getDeviceId();//imei=868943005484708
		return tm.getDeviceId();
	}

	/*
	 * MD5加密
	 */
	public static String getMD5Str(String str) {
		MessageDigest messageDigest = null;

		try {
			messageDigest = MessageDigest.getInstance("MD5");

			messageDigest.reset();

			messageDigest.update(str.getBytes("UTF-8"));
		} catch (NoSuchAlgorithmException e) {
			System.exit(-1);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		byte[] byteArray = messageDigest.digest();

		StringBuffer md5StrBuff = new StringBuffer();

		for (int i = 0; i < byteArray.length; i++) {
			if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)
				md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i]));
			else
				md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
		}
		// 16位加密，从第9位到25位
		return md5StrBuff.substring(8, 24).toString().toUpperCase();
	}

	/**
	 * 设置html格式的下划线
	 *
	 * @param text
	 *            需要设置的文本
	 * @return
	 */
	public static String setHtmlBottomLine(String text) {
		return "<u\">" + text + "</u>";
	}

	/**
	 * 设置Selector
	 * <p>
	 * 不需要设置 传-1
	 *
	 * @param context
	 * @param idNormal
	 * @param idPressed
	 * @param idFocused
	 * @param idUnable
	 * @return
	 */
	public static StateListDrawable newSelector(Context context, int idNormal, int idPressed, int idFocused,
			int idUnable) {
		StateListDrawable bg = new StateListDrawable();
		Drawable normal = idNormal == -1 ? null : context.getResources().getDrawable(idNormal);
		Drawable pressed = idPressed == -1 ? null : context.getResources().getDrawable(idPressed);
		Drawable focused = idFocused == -1 ? null : context.getResources().getDrawable(idFocused);
		Drawable unable = idUnable == -1 ? null : context.getResources().getDrawable(idUnable);
		// View.PRESSED_ENABLED_STATE_SET
		bg.addState(new int[] { android.R.attr.state_pressed, android.R.attr.state_enabled }, pressed);
		// View.ENABLED_FOCUSED_STATE_SET
		bg.addState(new int[] { android.R.attr.state_enabled, android.R.attr.state_focused }, focused);
		// View.ENABLED_STATE_SET
		bg.addState(new int[] { android.R.attr.state_enabled }, normal);
		// View.FOCUSED_STATE_SET
		bg.addState(new int[] { android.R.attr.state_focused }, focused);
		// View.WINDOW_FOCUSED_STATE_SET
		bg.addState(new int[] { android.R.attr.state_window_focused }, unable);
		// View.EMPTY_STATE_SET
		bg.addState(new int[] {}, normal);
		return bg;
	}

	/**
	 * 获取需要分享的Bitmap
	 *
	 * @return
	 */
	public static Bitmap getBitmap(Context context) {
		File file = Utils.getDiskCacheDir(context, "shareCapture");
		if (file.exists()) {
			return BitmapFactory.decodeFile(file.getAbsolutePath());
		}
		return null;
	}

	private static final DisplayMetrics displayMetrics = new DisplayMetrics();

	/**
	 * 返回屏幕宽(px)
	 */
	public static int getScreenWidth(Activity activity) {
		activity.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
		return displayMetrics.widthPixels;
	}

	/**
	 * 将Dip转换为px
	 *
	 * @param context
	 * @param dip
	 * @return
	 */
	public static int dip2px(Context context, float dip) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dip * scale + 0.5f);
	}

	/**
	 * 将sp转换为px
	 * 
	 * @param context
	 * @param spValue
	 * @return
	 */
	public static int sp2px(Context context, float spValue) {
		final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
		return (int) (spValue * fontScale + 0.5f);
	}

	/**
	 * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
	 */
	public static int px2dip(Context context, float pxValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (pxValue / scale + 0.5f);
	}

	public static Bitmap stringtoBitmap(String string) {
		// 将字符串转换成Bitmap类型
		Bitmap bitmap = null;
		try {
			byte[] bitmapArray;
			bitmapArray = Base64Util.decode(string);
			bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0, bitmapArray.length);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return bitmap;
	}

	public byte[] decode(String str) {
		byte[] data = str.getBytes();
		int len = data.length;
		ByteArrayOutputStream buf = new ByteArrayOutputStream(len);
		int i = 0;
		int b1, b2, b3, b4;

		while (i < len) {

			/* b1 */
			do {
				b1 = base64DecodeChars[data[i++]];
			} while (i < len && b1 == -1);
			if (b1 == -1) {
				break;
			}

			/* b2 */
			do {
				b2 = base64DecodeChars[data[i++]];
			} while (i < len && b2 == -1);
			if (b2 == -1) {
				break;
			}
			buf.write((int) ((b1 << 2) | ((b2 & 0x30) >>> 4)));

			/* b3 */
			do {
				b3 = data[i++];
				if (b3 == 61) {
					return buf.toByteArray();
				}
				b3 = base64DecodeChars[b3];
			} while (i < len && b3 == -1);
			if (b3 == -1) {
				break;
			}
			buf.write((int) (((b2 & 0x0f) << 4) | ((b3 & 0x3c) >>> 2)));

			/* b4 */
			do {
				b4 = data[i++];
				if (b4 == 61) {
					return buf.toByteArray();
				}
				b4 = base64DecodeChars[b4];
			} while (i < len && b4 == -1);
			if (b4 == -1) {
				break;
			}
			buf.write((int) (((b3 & 0x03) << 6) | b4));
		}
		return buf.toByteArray();
	}

	// 判断是否为手机号
	public static boolean checkPhoneNum(String phoneNum) {
		String regExp = "^[1]([0-9][0-9]{1}|59|58|88|89)[0-9]{8}$";
		Pattern p = Pattern.compile(regExp);
		Matcher m = p.matcher(phoneNum);
		return m.find();// boolean}
	}

	/**
	 * 获取应用安装时间(TS)秒数
	 *
	 * @return
	 */
	public static long getAppInstallTime(Context context) {

		// if (pushMessage.serial_number <
		// BabytreeUtil.getAppInstallTime(getApplicationContext())) {
		// continue;
		// }

		long ret = System.currentTimeMillis() / 1000;

		try {
			PackageManager pm = context.getPackageManager();
			ApplicationInfo appInfo = pm.getApplicationInfo(context.getPackageName(), 0);
			String appFile = appInfo.sourceDir;
			long installed = new File(appFile).lastModified(); // Ep
			if (installed != 0) {
				ret = installed / 1000;
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		return ret;
	}

	public static void writeSearchCache(ArrayList<String> contentList, String cachePath) {
		FileUtil fileUtil = new FileUtil();
		if (fileUtil.writeFileOOS(cachePath, contentList, false)) {

		}
	}

	public static ArrayList<String> readSearchCache(String cachePath) {
		FileUtil fileUtil = new FileUtil();
		Object obj = fileUtil.readFileOIS(cachePath);
		if (null != obj) {
			ArrayList<String> aas = (ArrayList<String>) obj;
			return aas;
		}
		return null;
	}

	/**
	 * 转换图片成圆形
	 *
	 * @param bitmap
	 *            传入Bitmap对象
	 * @return
	 */
	public static Bitmap toRoundBitmap(Bitmap bitmap) {
		int width = bitmap.getWidth();
		int height = bitmap.getHeight();
		float roundPx;
		float left, top, right, bottom, dst_left, dst_top, dst_right, dst_bottom;
		if (width <= height) {
			roundPx = width / 2;
			top = 0;
			bottom = width;
			left = 0;
			right = width;
			height = width;
			dst_left = 0;
			dst_top = 0;
			dst_right = width;
			dst_bottom = width;
		} else {
			roundPx = height / 2;
			float clip = (width - height) / 2;
			left = clip;
			right = width - clip;
			top = 0;
			bottom = height;
			width = height;
			dst_left = 0;
			dst_top = 0;
			dst_right = height;
			dst_bottom = height;
		}

		Bitmap output = Bitmap.createBitmap(width, height, Config.ARGB_8888);
		Canvas canvas = new Canvas(output);

		final int color = 0xff424242;
		final Paint paint = new Paint();
		final Rect src = new Rect((int) left, (int) top, (int) right, (int) bottom);
		final Rect dst = new Rect((int) dst_left, (int) dst_top, (int) dst_right, (int) dst_bottom);
		final RectF rectF = new RectF(dst);

		paint.setAntiAlias(true);

		canvas.drawARGB(0, 0, 0, 0);
		paint.setColor(color);
		canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

		paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
		canvas.drawBitmap(bitmap, src, dst, paint);
		return output;
	}

	public static Bitmap readFromDrawable(Context context, int id) {
		Resources res = context.getResources();
		Bitmap bitmap = BitmapFactory.decodeResource(res, id);
		return bitmap;
	}

	public static int fun2(String Str) {// 字符串转换为ASCII码
		int num = 0;
		if (Str != null) {
			char[] chars = Str.toCharArray(); // 把字符中转换为字符数组

			for (int i = 0; i < chars.length; i++) {// 输出结果
				if ((int) chars[i] > 127) {
					num = num + 2;
				} else {
					num = num + 1;
				}
			}
		}
		return num;
	}

	// 显示软键盘
	public static void popKeyBoard(final EditText edittext, final Context activity) {
		edittext.requestFocus(); // edittext是一个EditText控件
		Timer timer = new Timer(); // 设置定时器
		timer.schedule(new TimerTask() {
			@Override
			public void run() { // 弹出软键盘的代码
				InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
				imm.showSoftInput(edittext, InputMethodManager.RESULT_SHOWN);
				imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
			}
		}, 200); // 设置200毫秒的时长

	}

	// 显示软键盘
	public static void popKeyBoard1(final EditText edittext, final View view, final Context activity) {
		edittext.requestFocus(); // edittext是一个EditText控件
		Timer timer = new Timer(); // 设置定时器
		timer.schedule(new TimerTask() {
			@Override
			public void run() { // 弹出软键盘的代码
				InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
				imm.showSoftInput(edittext, InputMethodManager.RESULT_SHOWN);
				imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
				int[] a = new int[2];
				view.getLocationInWindow(a);
			}
		}, 200); // 设置200毫秒的时长

	}

	private static InputMethodManager imm;

	// 隐藏软键盘
	public static void hideKeyBoard(Context activity) {
		try {
			if (null == imm) {
				imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
			}
			if (imm.isActive()) {
				View view = ((Activity) activity).getCurrentFocus();
				if (view != null) {
					imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void hideKeyBoard(Context activity, View view) {

		if (null == imm) {
			imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
		}
		if (imm.isActive()) {
			imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
		}
	}

	public static boolean startsWithIgnoreCase(String string, String prefix) {
		if ((null == string) || (null == prefix)) {
			return false;
		}
		if (string.length() < prefix.length()) {
			return false;
		}
		String temp = string.substring(0, prefix.length());
		return temp.equalsIgnoreCase(prefix);
	}

	public static boolean isContainStr(String string, String prefix) {
		if ((null == string) || (null == prefix)) {
			return false;
		}
		if (string.length() < prefix.length()) {
			return false;
		}
		return string.contains(prefix);
	}

	public static boolean endsWithIgnoreCase(String string, String suffix) {
		if ((null == string) || (null == suffix)) {
			return false;
		}
		if (string.length() < suffix.length()) {
			return false;
		}
		String temp = string.substring(string.length() - suffix.length(), string.length());
		return temp.equalsIgnoreCase(suffix);
	}

	public static int getScreenHeight(Context context) {
		DisplayMetrics dm = new DisplayMetrics();
		((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(dm);
		return dm.heightPixels;
	}

	public static String utf8ToUnicode(String inStr) {
		char[] myBuffer = inStr.toCharArray();

		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < inStr.length(); i++) {
			UnicodeBlock ub = UnicodeBlock.of(myBuffer[i]);
			if (ub == UnicodeBlock.BASIC_LATIN) {
				// 英文及数字等
				sb.append(myBuffer[i]);
			} else if (ub == UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
				// 全角半角字符
				int j = (int) myBuffer[i] - 65248;
				sb.append((char) j);
			} else {
				// 汉字
				short s = (short) myBuffer[i];
				String hexS = Integer.toHexString(s);
				String unicode = "\\u" + hexS;
				sb.append(unicode.toLowerCase());
			}
		}
		return sb.toString();
	}

	public static String bytes2HexString(byte[] b) {
		String ret = "";
		for (int i = b.length - 1; i >= 0; i--) {
			String hex = Integer.toHexString(b[i] & 0xFF);
			if (hex.length() == 1) {
				hex = '0' + hex;
			}
			ret += hex.toLowerCase();
		}
		return ret;
	}

	/**
	 * 动态配置图片资源
	 *
	 * @param mContext
	 * @param pic_name
	 *            图片名字
	 * @return
	 */
	public static int getDrawbleResource(Context mContext, String pic_name) {
		ApplicationInfo appInfo = mContext.getApplicationInfo();
		// //得到该图片的id(name 是该图片的名字，"drawable"
		// 是该图片存放的目录，appInfo.packageName是应用程序的包)
		int resID = mContext.getResources().getIdentifier(pic_name, "drawable", appInfo.packageName);
		return resID;
	}

	public static boolean containsWithIgnoreCase(String string, String sub) {
		boolean result = false;
		if ((null != string) && (null != sub)) {
			String temp1 = string.toLowerCase(Locale.getDefault());
			String temp2 = sub.toLowerCase(Locale.getDefault());
			result = temp1.contains(temp2);
		}

		return result;
	}

	public static String decodeURIComponent(String encodedURI) {
		char actualChar;

		StringBuffer buffer = new StringBuffer();

		int bytePattern, sumb = 0;

		for (int i = 0, more = -1; i < encodedURI.length(); i++) {
			actualChar = encodedURI.charAt(i);

			switch (actualChar) {
			case '%': {
				actualChar = encodedURI.charAt(++i);
				int hb = (Character.isDigit(actualChar) ? actualChar - '0'
						: 10 + Character.toLowerCase(actualChar) - 'a') & 0xF;
				actualChar = encodedURI.charAt(++i);
				int lb = (Character.isDigit(actualChar) ? actualChar - '0'
						: 10 + Character.toLowerCase(actualChar) - 'a') & 0xF;
				bytePattern = (hb << 4) | lb;
				break;
			}
			case '+': {
				bytePattern = ' ';
				break;
			}
			default: {
				bytePattern = actualChar;
			}
			}

			if ((bytePattern & 0xc0) == 0x80) { // 10xxxxxx
				sumb = (sumb << 6) | (bytePattern & 0x3f);
				if (--more == 0)
					buffer.append((char) sumb);
			} else if ((bytePattern & 0x80) == 0x00) { // 0xxxxxxx
				buffer.append((char) bytePattern);
			} else if ((bytePattern & 0xe0) == 0xc0) { // 110xxxxx
				sumb = bytePattern & 0x1f;
				more = 1;
			} else if ((bytePattern & 0xf0) == 0xe0) { // 1110xxxx
				sumb = bytePattern & 0x0f;
				more = 2;
			} else if ((bytePattern & 0xf8) == 0xf0) { // 11110xxx
				sumb = bytePattern & 0x07;
				more = 3;
			} else if ((bytePattern & 0xfc) == 0xf8) { // 111110xx
				sumb = bytePattern & 0x03;
				more = 4;
			} else { // 1111110x
				sumb = bytePattern & 0x01;
				more = 5;
			}
		}
		return buffer.toString();
	}

	/**
	 * 解码操作.
	 *
	 * @param encodedUrl
	 * @return
	 */
	public static String decodeFinal(String encodedUrl) {
		return decodeURIComponent(decodeURIComponent(encodedUrl));
	}

	public static int isYearAgo(long pre_time, long cur_time) {
		int disYear = 0;
		try {
			String pre_Str = BallUtil.formatNYRtime(pre_time);
			String cur_Str = BallUtil.formatNYRtime(cur_time);
			String pre_year = pre_Str.substring(0, 4);
			String cur_year = cur_Str.substring(0, 4);

			disYear = ParseUtil.parseInteger(pre_year, 0) - ParseUtil.parseInteger(cur_year, 0);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return disYear;
	}

	public static String getPhotoPath(String path) {
		if (path != null && path.startsWith("/")) {
			path = "file://" + path;
		}
		return path;
	}

	public static String limitUserName(String name) {
		if (TextUtils.isEmpty(name)) {
			return "宝宝";
		}
		if (name.length() > 6) {
			name = name.substring(0, 6) + "...";
		}
		return name;
	}

	public static String limit12UserName(String name) {
		if (name != null && name.length() > 12) {
			name = name.substring(0, 12) + "...";
		}
		return name;
	}

	public static String limitNickName(String name, int length) {
		if (name != null && name.length() > length) {
			name = name.substring(0, length) + "...";
		}
		return name;
	}

	public static String limitNum(String name, int num) {
		if (name != null && name.length() > num) {
			name = name.substring(0, num - 1) + "...";

		}
		return name;
	}

	/**
	 * 截取url，去除&&title之后
	 * <p/>
	 * eg:http://2014jbopenclass.nimads.com/mobile/?&&title=成长宝典
	 *
	 * @param url
	 * @return
	 */
	public static String getSplitUrl(String url) {
		if (URLUtil.isNetworkUrl(url)) {
			int index = url.indexOf("&&title");
			BallLog.d("try to split web url:" + url);
			return index <= 0 ? url : url.substring(0, index);
		} else {
			return url;
		}
	}

	public static int parseInt(String value) {
		try {
			return Integer.parseInt(value);
		} catch (Exception e) {
			return 0;
		}
	}

	public static Long parseLong(String value) {
		try {
			return Long.parseLong(value);
		} catch (Exception e) {
			return 0L;
		}
	}

	public static Double parseDouble(String value) {
		try {
			return Double.parseDouble(value);
		} catch (Exception e) {
			return 0.0;
		}
	}

	/**
	 * 获取文件夹大小
	 *
	 * @param file
	 *            File实例
	 * @return long 单位为M
	 * @throws Exception
	 */
	public static long getFolderSize(File file) throws Exception {
		long size = 0;
		File[] fileList = file.listFiles();
		for (int i = 0; i < fileList.length; i++) {
			if (fileList[i].isDirectory()) {
				size = size + getFolderSize(fileList[i]);
			} else {
				size = size + fileList[i].length();
			}
		}
		// return size/1048576;
		return size;
	}

	/**
	 * 获取当前时间是星期几
	 */
	public static int getWeekDay(Date date) {
		int[] time = null;
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		return cal.get(Calendar.DAY_OF_WEEK);
	}

	public static long getCurImageTime(long imageDateTime) {
		String dateImage = BallUtil.formatNY(imageDateTime);

		SimpleDateFormat formatterTime = new SimpleDateFormat("HH:mm:ss", Locale.getDefault());
		Date currentTime = new Date();
		String timeString = formatterTime.format(currentTime);

		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
		Date s = null;
		try {
			s = formatter.parse(dateImage + " " + timeString);
			return s.getTime() / 1000;
		} catch (ParseException e) {
			e.printStackTrace();
		}

		return imageDateTime;
	}

	// 删除本地文件
	public static void deleteFile(File file) {

		if (file.exists()) { // 判断文件是否存在
			if (file.isFile()) { // 判断是否是文件
				file.delete(); // delete()方法 你应该知道 是删除的意思;
			} else if (file.isDirectory()) { // 否则如果它是一个目录
				File files[] = file.listFiles(); // 声明目录下所有的文件 files[];
				for (int i = 0; i < files.length; i++) { // 遍历目录下所有的文件
					deleteFile(files[i]); // 把每个文件 用这个方法进行迭代
				}
			}
			file.delete();
		} else {
		}
	}

	/**
	 * 检查是否是数字
	 */
	public static boolean checkIfNumber(String in) {
		try {
			Integer.parseInt(in);
		} catch (NumberFormatException ex) {
			return false;
		}
		return true;
	}

	/**
	 * 得到Dns解析ip
	 * 
	 * @return
	 */
	public static String getServerIp() {
		InetAddress address = null;
		String mAddress = "";
		try {
			address = InetAddress.getByName("www.babytree.com");
			mAddress = address.getHostAddress();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
		return mAddress;
	}

	/**
	 * 获取客户端ip地址
	 * 
	 * @return
	 */
	public static String getClientIp(Context appContext) {
		String ip = "";
		try {
			ConnectivityManager connectMgr = (ConnectivityManager) appContext
					.getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo info = connectMgr.getActiveNetworkInfo();
			if (info != null) {
				switch (info.getType()) {
				case ConnectivityManager.TYPE_WIFI:
					ip = getWifiIpAddress(appContext);
					break;
				case ConnectivityManager.TYPE_MOBILE:
					ip = getLocalIpAddress();
					break;
				default:
					break;

				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ip;
	}

	public static String getWifiIpAddress(Context appContext) {
		WifiManager wifiManager = (WifiManager) appContext.getSystemService(Context.WIFI_SERVICE);
		// 判断wifi是否开启
		if (!wifiManager.isWifiEnabled()) {
			wifiManager.setWifiEnabled(true);
		}
		WifiInfo wifiInfo = wifiManager.getConnectionInfo();
		int ipAddress = wifiInfo.getIpAddress();
		String ip = (ipAddress & 0xFF) + "." + ((ipAddress >> 8) & 0xFF) + "." + ((ipAddress >> 16) & 0xFF) + "."
				+ (ipAddress >> 24 & 0xFF);
		return ip;
	}

	public static String getLocalIpAddress() {
		try {
			for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
				NetworkInterface intf = en.nextElement();
				for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
					InetAddress inetAddress = enumIpAddr.nextElement();
					if (!inetAddress.isLoopbackAddress()) {
						return inetAddress.getHostAddress().toString();
					}
				}
			}
		} catch (SocketException ex) {
			Log.i("fyh", ex.toString());
		}
		return null;
	}

	public static String getNetType(Context context) {
		try {
			ConnectivityManager connectivity = (ConnectivityManager) context
					.getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo nwInfo = connectivity.getActiveNetworkInfo();
			if (nwInfo == null) {
				return "unknow";
			}
			return nwInfo.toString();
		} catch (Exception ex) {
			return "unknow";
		}
	}

	/**
	 * 图片高斯模糊计算方法
	 * 
	 * @param bitmap
	 * @param context
	 * @param radiusp
	 * @param scale
	 * @return
	 */
	@SuppressLint("NewApi")
	public static Bitmap blurBitmap(Bitmap bitmap, Context context, int radiusp, float scale) {
		// long startMs = System.currentTimeMillis();
		Bitmap outBitmap;
		try {
			int radius = radiusp;
			float scaleFactor = scale;
			Bitmap newBitmap = Bitmap.createBitmap((int) (bitmap.getWidth() / scaleFactor),
					(int) (bitmap.getHeight() / scaleFactor), Config.ARGB_8888);
			Canvas canvas = new Canvas(newBitmap);
			canvas.translate(0, 0);
			canvas.scale(1 / scaleFactor, 1 / scaleFactor);
			Paint paint = new Paint();
			paint.setFlags(Paint.FILTER_BITMAP_FLAG);
			canvas.drawBitmap(bitmap, 0, 0, paint);

			outBitmap = newBitmap.copy(newBitmap.getConfig(), true);
			if (radius < 1) {
				return (null);
			}
			int w = newBitmap.getWidth();
			int h = newBitmap.getHeight();
			int[] pix = new int[w * h];
			newBitmap.getPixels(pix, 0, w, 0, 0, w, h);
			int wm = w - 1;
			int hm = h - 1;
			int wh = w * h;
			int div = radius + radius + 1;
			int r[] = new int[wh];
			int g[] = new int[wh];
			int b[] = new int[wh];
			int rsum, gsum, bsum, x, y, i, p, yp, yi, yw;
			int vmin[] = new int[Math.max(w, h)];
			int divsum = (div + 1) >> 1;
			divsum *= divsum;
			int dv[] = new int[256 * divsum];
			for (i = 0; i < 256 * divsum; i++) {
				dv[i] = (i / divsum);
			}
			yw = yi = 0;
			int[][] stack = new int[div][3];
			int stackpointer;
			int stackstart;
			int[] sir;
			int rbs;
			int r1 = radius + 1;
			int routsum, goutsum, boutsum;
			int rinsum, ginsum, binsum;
			for (y = 0; y < h; y++) {
				rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0;
				for (i = -radius; i <= radius; i++) {
					p = pix[yi + Math.min(wm, Math.max(i, 0))];
					sir = stack[i + radius];
					sir[0] = (p & 0xff0000) >> 16;
					sir[1] = (p & 0x00ff00) >> 8;
					sir[2] = (p & 0x0000ff);
					rbs = r1 - Math.abs(i);
					rsum += sir[0] * rbs;
					gsum += sir[1] * rbs;
					bsum += sir[2] * rbs;
					if (i > 0) {
						rinsum += sir[0];
						ginsum += sir[1];
						binsum += sir[2];
					} else {
						routsum += sir[0];
						goutsum += sir[1];
						boutsum += sir[2];
					}
				}
				stackpointer = radius;

				for (x = 0; x < w; x++) {

					r[yi] = dv[rsum];
					g[yi] = dv[gsum];
					b[yi] = dv[bsum];

					rsum -= routsum;
					gsum -= goutsum;
					bsum -= boutsum;

					stackstart = stackpointer - radius + div;
					sir = stack[stackstart % div];

					routsum -= sir[0];
					goutsum -= sir[1];
					boutsum -= sir[2];

					if (y == 0) {
						vmin[x] = Math.min(x + radius + 1, wm);
					}
					p = pix[yw + vmin[x]];

					sir[0] = (p & 0xff0000) >> 16;
					sir[1] = (p & 0x00ff00) >> 8;
					sir[2] = (p & 0x0000ff);

					rinsum += sir[0];
					ginsum += sir[1];
					binsum += sir[2];

					rsum += rinsum;
					gsum += ginsum;
					bsum += binsum;

					stackpointer = (stackpointer + 1) % div;
					sir = stack[(stackpointer) % div];

					routsum += sir[0];
					goutsum += sir[1];
					boutsum += sir[2];

					rinsum -= sir[0];
					ginsum -= sir[1];
					binsum -= sir[2];

					yi++;
				}
				yw += w;
			}
			for (x = 0; x < w; x++) {
				rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0;
				yp = -radius * w;
				for (i = -radius; i <= radius; i++) {
					yi = Math.max(0, yp) + x;

					sir = stack[i + radius];

					sir[0] = r[yi];
					sir[1] = g[yi];
					sir[2] = b[yi];

					rbs = r1 - Math.abs(i);

					rsum += r[yi] * rbs;
					gsum += g[yi] * rbs;
					bsum += b[yi] * rbs;

					if (i > 0) {
						rinsum += sir[0];
						ginsum += sir[1];
						binsum += sir[2];
					} else {
						routsum += sir[0];
						goutsum += sir[1];
						boutsum += sir[2];
					}

					if (i < hm) {
						yp += w;
					}
				}
				yi = x;
				stackpointer = radius;
				for (y = 0; y < h; y++) {
					pix[yi] = (0xff000000 & pix[yi]) | (dv[rsum] << 16) | (dv[gsum] << 8) | dv[bsum];

					rsum -= routsum;
					gsum -= goutsum;
					bsum -= boutsum;

					stackstart = stackpointer - radius + div;
					sir = stack[stackstart % div];

					routsum -= sir[0];
					goutsum -= sir[1];
					boutsum -= sir[2];

					if (x == 0) {
						vmin[y] = Math.min(y + r1, hm) * w;
					}
					p = x + vmin[y];

					sir[0] = r[p];
					sir[1] = g[p];
					sir[2] = b[p];

					rinsum += sir[0];
					ginsum += sir[1];
					binsum += sir[2];

					rsum += rinsum;
					gsum += ginsum;
					bsum += binsum;

					stackpointer = (stackpointer + 1) % div;
					sir = stack[stackpointer];

					routsum += sir[0];
					goutsum += sir[1];
					boutsum += sir[2];

					rinsum -= sir[0];
					ginsum -= sir[1];
					binsum -= sir[2];

					yi += w;
				}
			}
			outBitmap.setPixels(pix, 0, w, 0, 0, w, h);
		} catch (Throwable e) {
			outBitmap = bitmap;
		}
		// Toast.makeText(context, "cost " + (System.currentTimeMillis() -
		// startMs) + "ms", 0).show();
		return outBitmap;

	}

	/**
	 * 获得状态栏的高度
	 *
	 * @param context
	 * @return
	 */
	public static int getStatusHeight(Context context) {

		int statusHeight = -1;
		try {
			Class<?> clazz = Class.forName("com.android.internal.R$dimen");
			Object object = clazz.newInstance();
			int height = Integer.parseInt(clazz.getField("status_bar_height").get(object).toString());
			statusHeight = context.getResources().getDimensionPixelSize(height);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return statusHeight;
	}

	/**
	 * 在某些经过简洁版本的Android系统中
	 * RunningAppProcessInfo.importance的值一直为IMPORTANCE_BACKGROUND. 记录是否为特殊这种系统
	 */
	private static boolean mIsSpecialSystem = false;

	/**
	 * 程序是否在前台运行
	 *
	 * @return
	 */
	public static boolean isAppOnForeground(Context context) {
		ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
		if (!mIsSpecialSystem) {
			try {
				boolean isSpecial = true;
				String packageName = context.getPackageName();
				List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
				if (null != appProcesses) {
					for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
						if (appProcess.processName.equals(packageName)) {
							if ((appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND)
									|| (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE)) {
								KeyguardManager keyguardManager = (KeyguardManager) context
										.getSystemService(Context.KEYGUARD_SERVICE);
								if (keyguardManager.inKeyguardRestrictedInputMode()) {
									return false;
								} else {
									return true;
								}
							}
						}
						if (isSpecial) {
							if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
								isSpecial = false;
							}
						}
					}
					if (isSpecial) {
						mIsSpecialSystem = true;
						return !isApplicationBroughtToBackgroundByTask(context, activityManager);
					}
				}
			} catch (Exception e) {
				BallLog.e("ldebug", "isAppOnForeground e[" + e + "]");
			}
		} else {
			return !isApplicationBroughtToBackgroundByTask(context, activityManager);
		}
		return false;
	}

	/**
	 * 判断当前应用程序是否处于后台，通过getRunningTasks的方式
	 *
	 * @return true 在后台; false 在前台
	 */
	public static boolean isApplicationBroughtToBackgroundByTask(Context context, ActivityManager activityManager) {
		try {
			List<ActivityManager.RunningTaskInfo> tasks = activityManager.getRunningTasks(1);
			if (!tasks.isEmpty()) {
				ComponentName topActivity = tasks.get(0).topActivity;
				if (!topActivity.getPackageName().equals(context.getPackageName())) {
					return true;
				}
			}
		} catch (Exception e) {
			BallLog.e("ldebug", "isApplicationBroughtToBackgroundByTask e[" + e + "]");
		}
		return false;
	}

	private static final String IMAGE_TYPE = "image/jpeg";
	private static final String IMAGE_TYPE_PNG = "image/png";

	public static Cursor getImageQueryCursor(ContentResolver resolver) {
		return resolver.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
				new String[] { MediaStore.Images.ImageColumns.DATA, // The data stream for the file
						MediaStore.Images.ImageColumns.DATE_TAKEN, // 照片拍摄时间
						MediaStore.Images.ImageColumns.DATE_ADDED, // The time the file was added to the
																	// media provider Units are seconds since 1970.
						MediaStore.Images.ImageColumns.LATITUDE, // 照片拍摄时所处地点的纬度
						MediaStore.Images.ImageColumns.LONGITUDE, // 照片拍摄时所处地点的经度
						MediaStore.Images.ImageColumns.MIME_TYPE },
				MediaStore.Images.ImageColumns.MIME_TYPE + "=" + "\"" + IMAGE_TYPE + "\"" + " OR "
						+ MediaStore.Images.ImageColumns.MIME_TYPE + "=" + "\"" + "image/jpg" + "\"" + " OR "
						+ MediaStore.Images.ImageColumns.MIME_TYPE + "=" + "\"" + IMAGE_TYPE_PNG
						+ "\""
								 /* + " AND (" +
								  MediaStore.Images.ImageColumns.DATA + " like " + "\'%Camera%\'" + " OR " +
								  MediaStore.Images.ImageColumns.DATA + " like " + "\'%DCIM%\'" + " OR " +
								  MediaStore.Images.ImageColumns.DATA + " like " + "\'%相机%\')"*/
								 ,
				null, MediaStore.Images.ImageColumns.DATE_TAKEN + " DESC");
	}

	/**
	 * 缓存非绝对路径
	 */
	public static final String CACHE_STORE_PATH = "/.zaiwan/cache/";

	// Bitmap对象保存为图片文件
	public static void storePicFile(Context context, Bitmap bitmap, String fileName) {

		if (FolderOper.isExistSdcard(context)) {
			// 创建文件夹
			try {
				FolderOper.createSDCardDir(CACHE_STORE_PATH);
				File iconFile = new File(fileName);
				// if (!iconFile.exists()) {
				// iconFile.mkdirs();
				// }
				BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(iconFile));
				bitmap.compress(Bitmap.CompressFormat.PNG, 95, stream);
				bitmap.recycle();
				bitmap = null;
				stream.flush();
				stream.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	public static boolean isLogin(Context context) {
		if (!TextUtils.isEmpty(SharedPreferencesUtil.getStringValue(context, KeysConstans.USER_ID))) {
			return true;
		}
		return false;
	}

	public static boolean getEditCount(String content, int length) {
		boolean isSuccess = false;
		int eCount = 0;
		try {
			int count = new String(content.getBytes("gb2312"), "iso-8859-1").length() / 2;
			eCount = length - count;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		if (eCount >= 0) {
			isSuccess = true;
		}
		return isSuccess;
	}

	public static boolean isNum(String content) {
		Pattern p = Pattern.compile("[0-9]*");
		Matcher m = p.matcher(content);
		if (m.matches()) {
			return true;
		} else {
			return false;
		}
	}

	public static boolean isEG(String content) {
		Pattern p = Pattern.compile("[a-zA-Z]");
		Matcher m = p.matcher(content);
		if (m.matches()) {
			return true;
		} else {
			return false;
		}
	}

	public static boolean isZH(String content) {
		Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
		Matcher m = p.matcher(content);
		if (m.matches()) {
			return true;
		} else {
			return false;
		}
	}
}